import vix from '@bairong/vix'
import {
  CAPTCHA, LOGIN, LOGIN_OUT, AUTH
} from './urls'

const { request } = vix

// 验证码接口
export function getCaptchaApi() {
  return request({
    url: CAPTCHA,
    method: 'get'
  })
}

export interface LoginRes {
  id: string
  sessionid: string
  realName: string
}

export function loginApi(data: object) {
  return new Promise((resolve, reject) => {
    (request({
      url: LOGIN,
      method: 'post',
      data
    }) as any).then((res: LoginRes) => {
      resolve({
        id: res.id,
        token: res.sessionid,
        userName: res.realName,
        realName: res.realName
      })
    }).catch((err: Error) => {
      reject(err)
    })
  })
}

export function getPermissonsApi(data: object) {
  return new Promise((resolve, reject) => {
    (request({
      url: AUTH,
      method: 'get',
      data
    }) as any).then((res: { resourcesList: [] }) => {
      const { resourcesList } = res
      // 过滤本系统的路由权限
      const menus = resourcesList
        .filter((resource: { category: number }) => resource.category === 1 || resource.category === 2)
        .map((v: { englishName: string }) => ({ code: v.englishName }))
      const operates = resourcesList
        .filter((resource: { category: number }) => resource.category === 4)
        .map((v: { englishName: string }) => ({ code: v.englishName }))
      resolve({
        menus,
        operates
      })
    }).catch((err: Error) => {
      reject(err)
    })
  })
}

export function logoutApi(data: object) {
  return request({
    url: LOGIN_OUT,
    method: 'get',
    data
  })
}
